package com.younio.local.compnent;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @author lan [1728209643@qq.com]
 * @desc ws, 客户端连接地址<a>ws://localhost:8081/api/local/ws/{name}</a>
 * @create 2019/1/2 8:54
 */
@Slf4j
@Component
@SuppressWarnings("unchecked")
@ServerEndpoint(value = "/ws/{name}")
public class WebSocketServer {

    private static final ConcurrentMap<String, Session> sessionMap = new ConcurrentHashMap<>();

    @OnClose
    public void onClose(Session session, @PathParam("name") String name) {
        log.info("[{}] leave from websocket server.", name);
        synchronized (sessionMap) {
            sessionMap.remove(name);
        }
    }

    @OnOpen
    public void onOpen(Session session, @PathParam("name") String name) {
        log.info("Client [{}] connected to WebSocket Server", name);
        synchronized (sessionMap) {
            sessionMap.put(name, session);
        }
    }

    public void broadcast(String message) {
        synchronized (sessionMap) {
            sessionMap.forEach((k, session) -> {
                try {
                    session.getBasicRemote().sendText(message);
                } catch (Exception e) {
                    log.info("向{}发送消息失败", k);
                }
            });
        }
    }

}
